#include "rf_module.h"
#include "includes.h"
#include "drivers.h"

//#define RF_MODULE_NEW               1

#ifdef RF_MODULE_NEW

#define HI_DURATION_US              800
#define LO_DURATION_US              1600
#else
#define HI_DURATION_US              4000
#define LO_DURATION_US              800
#endif


#define SET_LOW()                   GPIO_ResetBits(GPIOC, GPIO_Pin_14)
#define SET_HIGH()                  GPIO_SetBits(GPIOC, GPIO_Pin_14)

#define rf_delay_us                 bsp_DelayUS

#define RF_REPEAT_COUNT             8

uint8_t mPoweron = FALSE;

void rf_module_init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    //poweron immo module
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 |GPIO_Pin_14;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);

    GPIO_ResetBits(GPIOC, GPIO_Pin_13);
    GPIO_ResetBits(GPIOC, GPIO_Pin_14);
}

void rf_module_poweron(void)
{
    GPIO_SetBits(GPIOC, GPIO_Pin_13);
    mPoweron = TRUE;
}

void rf_module_poweroff(void)
{
    mPoweron = FALSE;
    GPIO_ResetBits(GPIOC, GPIO_Pin_13);
    SET_LOW();
}

void rf_send_high(void)
{
    SET_HIGH();
    rf_delay_us(HI_DURATION_US);
    SET_LOW();
    rf_delay_us(LO_DURATION_US);
}
void rf_send_low(void)
{
    SET_HIGH();
    rf_delay_us(LO_DURATION_US);
    SET_LOW();
    rf_delay_us(HI_DURATION_US);
}

void rf_send_start(void)
{
    SET_HIGH();
    rf_delay_us(400);
    SET_LOW();
    rf_delay_us(12400);
}

void rf_send(int data)
{
    s8 i;
    int address = data;
    for(i = 7; i >= 0; i--) {
        if((address >> i) & 0x01) {
            rf_send_high();
        } else {
            rf_send_low();
        }
    }
}

void rf_lock(void)
{
    uint8_t i;

    if(!mPoweron)
        return;

    for(i = 0; i < RF_REPEAT_COUNT; i++) {
        rf_send_start();
#ifdef RF_MODULE_NEW
        rf_send(0x11);
        rf_send(0x22);
        rf_send(0x33);
#endif
        rf_send(IMMO_LOCK);
    }
}

void rf_unlock(void)
{
    uint8_t i;

    if(!mPoweron)
        return;

    for(i = 0; i < RF_REPEAT_COUNT; i++) {
        rf_send_start();
#ifdef RF_MODULE_NEW
        rf_send(0x11);
        rf_send(0x22);
        rf_send(0x33);
#endif
        rf_send(IMMO_UNLOCK);
    }
}

